#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define SIZE 4096
enum{
    SOCK_ERR=1,
    CONNECT_ERR,
};

void Usage(std::string proc){
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[]){
    if(argc != 3){
        Usage(argv[0]);
        exit(0);
    }
    // 获取服务端的IP地址和端口号
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 填充服务端的网络地址结构体
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while (true)
    {
        // 创建client socket
        int sockfd = 0;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "client socket create error..." << std::endl;
            exit(SOCK_ERR);
        }

        int cnt = 5;
        int isreconnect = false;

        // 连接bind client socket 由系统完成bind 随机端口

        do
        {
            // 客户端发起connect的时候，进行自动随机bind
            int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isreconnect = true;
                cnt--;
                std::cerr << "client connect error..., reconnect: "<< cnt << std::endl;
                sleep(2);
            }
            else{
                break;
            }
        } while (cnt && isreconnect);

        if(cnt == 0){
            std::cerr << "user ofline..." << std::endl;
            break;
        }

        // 进行通信
        std::string message;
        while (true){
            std::cout << "Please Enter@ ";
            getline(std::cin, message);

            // 发送信息到服务端
            ssize_t s = write(sockfd, message.c_str(), message.size());
            if (s < 0)
            {
                std::cout << "client write error!" << std::endl;
                continue;
            }

            // 接收处理后的信息
            char buffer[SIZE];
            ssize_t k = read(sockfd, buffer, sizeof(buffer));
            if (k > 0)
            {
                buffer[k] = 0;
                std::cerr << buffer << std::endl;
            }
            else if (k == 0)
            {
                std::cout << "client reconnect!" << std::endl;
                break;
            }
            else
            {
                std::cerr << "client read error!" << std::endl;
                break;
            }
        }

        // 关闭套接字描述符
        close(sockfd);
    }

    return 0;
}